package com.example.microservicefile.controller;

import com.example.microservicefile.utils.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api")
public class FileController {

    static Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    RandomUtils randomUtils;



    @Value("${file.image.path}")
    String IMAGE_PATH;

    @PostMapping("upload")
    public String upload(@RequestParam("file")MultipartFile file,@RequestParam("path") String filePath) throws IOException {
        String fileName=file.getOriginalFilename();
        logger.info("fileName:{}",fileName);
        logger.info("filePath:{}",filePath);

        File file2=new File(filePath);
        if  (!file2.exists()  && !file2.isDirectory())
        {
            logger.info("filePath does not exist:{}",filePath);
            file2.mkdirs();
        } else
        {
            logger.info("filepath exists");
        }
        String newName=randomUtils.getRandomString(20);

        String suffix= null;
        if (fileName != null) {
            suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        }

        String newFileName =newName+'.'+suffix;

        String FileTo=filePath+newFileName ;
        logger.info(FileTo);
        File to=new File(FileTo);
        file.transferTo(to);
        return newFileName ;
    }
}
